package com.hcy.rabbitbasicutils.utils;

/**
 * @Author huchenying
 * @Description
 * @Date 2021/12/27 18:09
 */
//高德api
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcy.common.dto.request.DirectionRequestDTO;
import com.hcy.common.dto.request.TrackInfoRequestDTO;
import com.hcy.common.dto.response.TrackInfoResponseDTO;
import com.hcy.rabbitbasicmodel.dto.UploadOrderTrackPointsDTO;
import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import com.hcy.rabbitbasicmodel.model.ReturnResult;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class GaoDeUtils {

    Logger logger = LoggerFactory.getLogger(GaoDeUtils.class);

    public static final Integer SID = 538258;

    @Autowired
    MyHttpUtils myHttpUtils;
    /**
     * @Author huchenying
     * @Description 返回距离 米
     * @Date  2021/12/29 14:12
     **/
    public Integer getDistance(String origin,String destination){
        logger.info("compute distance origin = {}, destination = {}", origin,destination);
        return doGetDistance(origin,destination);
    }
    public Integer getDistance(String startLat,String startLog,String endLat,String endLog){
        logger.info("compute distance origin = {}, destination = {}", startLat + "," + startLog,endLat + "," + endLog);
        return doGetDistance(startLog + "," + startLat, endLog + "," +endLat);
    }
    public Integer doGetDistance(String origin,String destination){
        String url =  "https://restapi.amap.com/v5/direction/driving";
        Map<String, Object> params = new HashMap<>();
        params.put("key","5c940527e7a1a30ebf63600e3645adfc");
        params.put("origin",origin);
        params.put("destination",destination);

        ResponseData<Object> responseData = myHttpUtils.sendGetRequest(url,params);
        if(responseData.getCode() == Code.Success){
            try {
                logger.info("result _ > {}",ToStringBuilder.reflectionToString(responseData));
                Object data = responseData.getData();
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(data));
                Integer distance = jsonObject.getJSONObject("route").getJSONArray("paths").getJSONObject(0).getInteger("distance");
                logger.info("distance = [{}]",distance);
                return distance;
            } catch (Exception e) {
                logger.error("计算距离 error -> {}",ToStringBuilder.reflectionToString(e));
                return null;
            }
        }else{
            return null;
        }
    }
    public ResponseData<Object>  direction(@Validated @RequestBody DirectionRequestDTO directionRequestDTO){
        logger.info("direction start param -> {}", org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(directionRequestDTO));
        String url = "https://restapi.amap.com/v5/direction/driving";
        Map<String, Object> map = new HashMap<>();
        map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.put("origin", directionRequestDTO.getOrigin());
        map.put("destination", directionRequestDTO.getDestination());
        map.put("origin_type", 0);
        map.put("show_fields", "polyline");
        return myHttpUtils.sendGetRequest(url, map);
    }

    /**
     * @Author huchenying
     * @Description 获取最短距离
     * @Date 2022/3/25 18:45
     **/
    public ResponseData<Integer[]>  directionShortest(String origin,String target){
        logger.info("directionShortest start param -> {},{}", origin,target);
        ResponseData<Integer[]> responseData2 = new ResponseData<>();
        String url = "https://restapi.amap.com/v5/direction/driving";
        Map<String, Object> map = new HashMap<>();
        map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.put("origin", origin);
        map.put("destination",target);
        map.put("origin_type", 0);
        map.put("show_fields", "polyline,cost");
        ResponseData<Object> responseData = myHttpUtils.sendGetRequest(url, map);
        if(responseData.getCode() == Code.Success){
            Object data = responseData.getData();
            //解析结果，获取最短路径
            JSONObject res = JSONObject.parseObject(JSON.toJSONString(data));
            JSONObject route = res.getJSONObject("route");
            JSONArray paths = route.getJSONArray("paths");
            JSONObject path = paths.getJSONObject(0);
            Integer distance = path.getInteger("distance");
            JSONObject cost = path.getJSONObject("cost");
            Integer duration = cost.getInteger("duration");
            responseData2.setCode(Code.Success);
            Integer[] integers = new Integer[2];
            integers[0] = distance;
            integers[1] = duration;
            responseData2.setData(integers);
        }else{
            responseData2.setCode(Code.Fail);
        }
        return responseData2;
    }

    /**
     * @Author huchenying
     * @Description 获取轨迹结果
     * @Date 2022/3/30 18:01
     **/
    public ResponseData<TrackInfoResponseDTO> getTrackByTrid(int tid,Long trid) {
        logger.info("getTrackByTrid start param -> {} ,{}",tid,trid);
        ResponseData<TrackInfoResponseDTO> responseData = new ResponseData<>();
        String url = "https://tsapi.amap.com/v1/track/terminal/trsearch";
        Map<String, Object> map = new HashMap<>();
        map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.put("sid", SID);
        map.put("tid", tid);
        map.put("trid", trid);
        ResponseData<Object> res = myHttpUtils.sendGetRequest(url, map);
        logger.info("orgin res -> {}", org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(res));
        if (res.getCode() == Code.Success) {
            try {
                Object data = res.getData();
                String s = JSONObject.toJSONString(data);
                JSONObject jsonObject = JSON.parseObject(s).getJSONObject("data");
                JSONArray tracks = jsonObject.getJSONArray("tracks");
                JSONObject jsonObject1 = tracks.getJSONObject(0);
                Integer distance = jsonObject1.getInteger("distance");
                Long time = jsonObject1.getLong("time");
                TrackInfoResponseDTO trackInfoResponseDTO = new TrackInfoResponseDTO();
                trackInfoResponseDTO.setDistance(distance);
                trackInfoResponseDTO.setTime(time);
                trackInfoResponseDTO.setTrid(trid);
                logger.info("查询track结果 -> {}", org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(trackInfoResponseDTO));
                responseData.setData(trackInfoResponseDTO);
                responseData.setCode(Code.Success);
            } catch (Exception e) {
                logger.error("解析轨迹查询结果时发生异常", e);
                responseData.setCode(Code.Fail);
                responseData.setMsg("结果解析异常");
            }
        } else {
            responseData.setCode(Code.Fail);
            responseData.setMsg(res.getMsg());
        }
        return responseData;
    }

    /**
     * @Author huchenying
     * @Description 搜索地址
     * @Date 2022/5/11 19:57
     **/
    public JSONArray searchAddress(String keyword){

        String url = "https://restapi.amap.com/v5/place/text";
        HashMap<String,Object> map = new HashMap<>();

        map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.put("keywords", keyword);
        ResponseData<Object> responseData = myHttpUtils.sendGetRequest(url, map);
        Object data = responseData.getData();
        String s = JSON.toJSONString(data);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray pois = jsonObject.getJSONArray("pois");
        return pois;
    }


    /**
     * @Author huchenying
     * @Description 上传订单轨迹
     * @Date 2022/3/30 22:13
     **/
    public void uploadTrackPoints(Integer tid,Integer trid,JSONArray points) {
        String url = "https://tsapi.amap.com/v1/track/point/upload";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();

        JSONArray loc = new JSONArray();
        for (int i = 0;i < points.size();i ++) {
            JSONObject jsonObject = points.getJSONObject(i);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("location",jsonObject.getString("longitude") + "," + jsonObject.getString("latitude"));
            jsonObject1.put("locatetime",jsonObject.getString("locatetime"));
            loc.add(jsonObject1);
        }
        String ps = JSON.toJSONString(loc);
        map.add("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.add("sid", SID);
        map.add("tid", tid);
        map.add("trid", trid);
        map.add("points",ps);
        logger.info("points -> {}",ps);
        myHttpUtils.sendPostRequest(url, map, new LinkedMultiValueMap<>());
    }

    public Integer addCar(String id) {
        String url = "https://tsapi.amap.com/v1/track/terminal/add";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.add("sid", SID);
        map.add("name", id);
        ReturnResult returnResult = myHttpUtils.sendPostRequest(url, map, new LinkedMultiValueMap<>());
        Object data = returnResult.getData();
        String s = JSON.toJSONString(data);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject data1 = jsonObject.getJSONObject("data");
        return data1.getInteger("tid");
    }
}
